package emulator.hardware.io.peripherals.iec;

public class DataReceiver {
	private static final int CLOCK_TIMEOUT = 300;
	private boolean eoi = false;
	private int data = 0;
	
	public boolean getEoi() { return eoi; }
	public int getData() { return data; }
	protected boolean receiveByte(boolean is_atn, IecSim iecSim)
			throws TimeoutException {
		data = 0;
		if (iecSim.waitClockOrAtn(true, is_atn))
			return false;
		iecSim.logState("RTS");
		iecSim.port.setBusData(true);
		// Receive data
		try {
			iecSim.waitClockLine(false, CLOCK_TIMEOUT);
		}
		catch (TimeoutException t)
		{
			iecSim.logState("EOI");
			this.eoi = true;
			iecSim.signalAck();
			iecSim.waitClockLine(false, CLOCK_TIMEOUT);
		}
		iecSim.logState("BIN");
		for (int i = 0; i < 8; i++)
		{
			iecSim.waitClockLine(true, CLOCK_TIMEOUT);
			iecSim.logState("BIT"+i);
			boolean in_bit = iecSim.port.getData();
			if (in_bit == true)
				data |= 1 << i;
			iecSim.waitClockLine(false, CLOCK_TIMEOUT);
		}
		iecSim.logState("FRM");
		iecSim.reportByte("->", is_atn, getData());
		return true;
	}
}
